package com.chinatelecom.ifree.business.service.order.impl;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.chinatelecom.ifree.business.dao.order.FcodeDao;
import com.chinatelecom.ifree.business.dao.order.FileDetailEntityDao;
import com.chinatelecom.ifree.business.dao.order.FileEntityDao;
import com.chinatelecom.ifree.business.domain.base.BoolResult;
import com.chinatelecom.ifree.business.domain.order.FcodeEntity;
import com.chinatelecom.ifree.business.domain.order.FcodeStatus;
import com.chinatelecom.ifree.business.domain.order.FileDetailEntity;
import com.chinatelecom.ifree.business.domain.order.FileEntity;
import com.chinatelecom.ifree.business.service.order.FcodeService;
import com.chinatelecom.ifree.business.util.BaseResult;

@Service
public class FcodeServiceImpl implements FcodeService {
	private static transient Logger logger = LoggerFactory.getLogger(FcodeServiceImpl.class);
	@Resource
	private FileEntityDao fileEntityDao;
	@Resource
	private FileDetailEntityDao fileDetailEntityDao;
	@Resource
	private FcodeDao fcodeDao;

	@Override
	@Transactional
	public BoolResult saveFcode(String filePath) {
		BoolResult result = new BoolResult();
		result.setResult(false);
		// 判断是否为一个可读文件，且文件名为.txt格式
		File file = new File(filePath);
		File[] files = file.listFiles(new FilenameFilter() {
			@Override
			public boolean accept(File dir, String name) {
				if (StringUtils.endsWith(name, ".txt"))
					return true;
				else
					return false;
			}
		});
		if (files != null && files.length > 0) {
			for (File f : files) {
				if (f.isFile() && f.canRead()) {
					if (f.length() > 0) {
						// 判断文件是否超过最大值 5M
						if (f.length() < 1024 * 1024 * 1024 * 5) {
							List<String> contents = null;
							try {
								// 读取到的文件内容
								contents = FileUtils.readLines(f, "UTF-8");
							} catch (IOException e) {
								logger.error(" FileUtils.readLines", e);
								result.setCode(BaseResult.ORDER_FILE_READ_ERROR.getCode());
								result.setMsg(BaseResult.ORDER_FILE_READ_ERROR.getMsg());
								return result;
							}
							long succCount = 0;// 保存文件处理记录
							String batchId = DateFormatUtils.format(new Date(), "yyyyMMddHHmmss");// 处理批次
							for (String content : contents) {
								if (StringUtils.isNotEmpty(StringUtils.trimToEmpty(content))) {
									FileDetailEntity detail = new FileDetailEntity();// 处理明细
									detail.setBatchId(batchId);
									detail.setContent(content);
									try {
										// 将文件内容存入FCODE表
										FcodeEntity entity = new FcodeEntity();
										entity.setFcode(content);
										entity.setStatus(FcodeStatus.INIT);
										entity.setCreateTimes(new Timestamp(System.currentTimeMillis()));
										if (logger.isInfoEnabled())
											logger.info("saveFcode===fcode={}", entity);
										fcodeDao.saveFcode(entity);
										succCount++;
										detail.setStatus(0);
									} catch (Exception e) {
										logger.error("saveFcode", e);
										detail.setStatus(1);
										detail.setErrorMsg(e.getMessage());
									}
									try {
										// 将文件处理情况存入明细表
										fileDetailEntityDao.saveFileDetail(detail);
									} catch (Exception e) {
										logger.error("saveFileDetail", e);
									}
								}
							}
							try {
								FileEntity fileEntity = new FileEntity();
								fileEntity.setBatchId(batchId);
								fileEntity.setFileName(f.getName());
								fileEntity.setTotalRecord(contents.size());
								fileEntity.setTotalHanldRecord(contents.size());
								fileEntity.setTotalSuccRecord(succCount);
								fileEntity.setTotalFailRecord(contents.size() - succCount);
								fileEntity.setOperator("admin");
								fileEntity.setCreateTime(new Timestamp(System.currentTimeMillis()));
								fileEntityDao.saveFileEntity(fileEntity);
								result.setResult(true);
							} catch (Exception e) {
								logger.error("saveFileEntity==saveBatchFileDetail", e);
								result.setCode(BaseResult.ORDER_FILE_LOG_ERROR.getCode());
								result.setMsg(BaseResult.ORDER_FILE_LOG_ERROR.getMsg());
							}
						} else {
							result.setCode(BaseResult.ORDER_FILE_LENGTH_ERROR.getCode());
							result.setMsg(BaseResult.ORDER_FILE_LENGTH_ERROR.getMsg());
						}

					} else {
						result.setCode(BaseResult.ORDER_FILE_EMPTY_ERROR.getCode());
						result.setMsg(BaseResult.ORDER_FILE_EMPTY_ERROR.getMsg());
					}
				} else {
					result.setCode(BaseResult.ORDER_FILE_CONTENT_ERROR.getCode());
					result.setMsg(BaseResult.ORDER_FILE_CONTENT_ERROR.getMsg());
				}
			}
		} else {
			result.setCode(BaseResult.ORDER_FILE_FORMAT_ERROR.getCode());
			result.setMsg(BaseResult.ORDER_FILE_FORMAT_ERROR.getMsg());
		}
		return result;
	}
}
